let sortWeightId = "frm-lose-weight";
//type:0:称重；1:报损
let sortTyp = 1;
$(document).ready(function () {
    $('.merger-title').hide();
    $('[data-toggle="tooltip"]').tooltip();
    //报损显示弹窗
    $('#frm-lose-model').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // 触发事件的按钮
        var recipient = button.data('whatever'); // 解析出data-whatever内容
        if (recipient) {
            var modal = $(this);
            modal.find('.modal-title').text('Message To ' + recipient);
            modal.find('.modal-body input').val(recipient);
        }
    });

    //报损隐藏弹窗
    $('#frm-lose-model').on('hide.bs.modal', function (event) {
        $('#goods-detail-id').val("");
        $('#frm-lose-weight').val("");
        $('#frm-lose-select').selectpicker('val', ['noneSelectedText']);
    });

    //报损下拉
    // $('#frm-lose-select').selectpicker('render');
    $("#frm-lose-select").on("changed.bs.select", function (e) {
        let temp = $(this).val();
        $('#goods-detail-id').val(temp);
    });
});

function storageDoneCallBack(data, cancel, opt) {
    if (!cancel) {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }
    }
}

//回调处理
function weighRespCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log(">>>>>>>>>>称重回调");
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        $("#empty-btn").hide();
    } else {
        const obj = data.data;
        delResponseFromWcs(data, opt);
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }

    }
}

//发送指令响应回调
function wcsToWmsResponseCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    if (cancel) {
        //todo 隐藏操作按钮等之类的
        // dealWithError("emptyNumber",'');
    } else {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        console.log("KKKKKK:" + JSON.stringify(obj));
        if (obj.code == 1) {
            const mergeBoxCode = $('#merge-box-code').text();
            if (!mergeBoxCode) {
                //是主箱则重新展示
                $('#' + obj.boxCode).hide();
            } else if (obj.boxCode == mergeBoxCode) {
                $('#' + obj.boxCode).hide();
            } else {
                //是拿空的货箱，重新展示空箱入库按钮
                $('#' + obj.boxCode).show();
            }
            $('#merge-box-up').show();
            if ((obj.totalWeight && obj.totalWeight > 0) || (obj.actWeight && obj.actWeight > 0)) {
                BootstrapDialog.alert(obj.msg + ",称重重量：" + obj.totalWeight + "；实际重量：" + obj.actWeight);
            } else {
                BootstrapDialog.alert(obj.msg);
            }

        } else {

        }
        setTimeout("$('#message-content').text('')", 7000);
    }
}

//分拣称重
function sortWeightCallBack(data, cancel, opt) {
    if (!data) {
        return;
    }
    console.log("分拣称重响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
        } else {
            $('#message-content').text(obj.msg);
            setTimeout("$('#message-content').text('')", 5000);
        }
    }
}

//货箱离开库位
function leaveBufferPosCallBack(data, cancel, opt) {

    if (!data) {
        return;
    }
    console.log("入库离开缓存位响应：" + JSON.stringify(data));
    if (!cancel) {
        delResponseFromWcs(data, opt);
        const obj = data.data;
        if (obj.code == 0) {
            const mergeBoxCode = $('#merge-box-code').text();
            const opt = {boxCode: obj.boxCode, clientId: $('#client-id').val()};
            $.ajax({
                type: "POST",
                url: "/wcs/sale/order/return/back",
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(opt),
                dataType: "json",
                success: function (data) {
                    if (data.code == 0) {
                        $('#ware-box-code').val("");
                        $('#goods-box-code').val("");
                        $('#merge-box-code').text("");
                        $('#merge-box-list').bootstrapTable('removeAll');
                        // $('#merge-table-list').bootstrapTable('removeAll');
                        $('#merge-btn').show();
                        $('#merge-box-up').hide();
                    } else {
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    BootstrapDialog.alert({
                        title: "信息提示！",
                        closable: false,
                        message: XMLHttpRequest.responseJSON.msg
                    });
                }
            });
        } else {
            BootstrapDialog.alert(obj.msg);
        }
    }
}

let actTemperatureCode;

//出库到缓存位
function inBufferPosCallBack(data, cancel, opt) {
    if (!data) {
        merge(false, 0, false);
        return;
    }
    if (!cancel) {
        //todo 逻辑处理
        const obj = data.data;
        console.log("ooooooooooooo:" + JSON.stringify(obj));
        if (obj.code == 0) {
            $("#temp-name").text(" " + obj.data.goodsBox.temperatureName);
            actTemperatureCode = obj.data.goodsBox.actTemperatureCode;
            const list = new Array();
            initOutBoxList(list);
            selectMergeBox(false, obj.boxCode);
            const mergeBoxCode = $('#merge-box-code').text(obj.boxCode);
            $('#merge-btn').show();
            $('#merge-box-up').show();
            $('#sort-box-up-force').show();
        } else {
            delResponseFromWcs(data, opt);
        }

    } else {
        //todo 按钮隐藏之类的
    }
}

function merge(flag, boxCode, clickButton) {
    if (flag) {
        let txt = "";
        if (clickButton === false) {
            txt = "若需退货入库，则点击去确定按钮，且进入页面后点击下架货箱按钮";
        } else {
            $('#merge-btn').hide();
        }
        BootstrapDialog.confirm({
            title: "信息提示",
            message: "是否要执行退货入库操作?" + txt,
            btnCancelLabel: '返回',
            btnOKLabel: '确定',
            callback: function (result) {
                // 点击确定按钮时，result为true
                if (result) {
                    //进入页面，不下架，进入页面点击合箱按钮则下架
                    selectMergeBox(flag, boxCode);
                } else {
                    // 刷新父级页面
                    parent.location.reload();
                }
            }
        });
    } else {
        selectMergeBox(flag, boxCode);
    }
}

function selectMergeBox(flag, boxCode) {
    $('.merger-title').show();
    const clientId = $('#client-id').val();
    const opt = $("#form-param").serializeJSON();
    $.ajax({
        type: "POST",
        url: "/wcs/sale/order/return/list",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        // async: false,
        success: function (data) {
            console.log("sd:" + JSON.stringify(data));
            if (data.code == 0) {
                initMergeBoxDetailList(data.data);
                initOutBoxList(new Array());
                if (data.data && data.data.length > 0) {
                    if (flag) {
                        downloadBox(clientId);
                    }

                    /*// initOutBoxList(data.data);
                    if (!flag) {
                        //最后一个货箱不显示空箱入库
                        const boxList = $('#merge-box-list').bootstrapTable('getData');
                        console.log("boxList:" + JSON.stringify(boxList));
                        if (boxList && boxList.length > 0 && boxCode && boxCode != 0) {
                            const size = boxList.length - 1;
                            console.log("size:" + size);
                            if (size == 0) {
                                $('#merge-box-code').text(boxList[0].boxCode);
                                return;
                            } else {
                                $('#merge-box-code').text(boxList[size].boxCode);
                            }
                            /!*for (let i = 0; i < size; i++) {
                                console.log(JSON.stringify(boxList[i]));
                                $('#' + boxCode).show();
                            }*!/
                        }
                    }*/
                }
            } else {
                BootstrapDialog.alert(data.msg);
                $('#merge-btn').show();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

/**
 * 下架货箱
 * @param clientId
 */
function downloadBox(clientId) {
    $.ajax({
        type: "POST",
        url: "/wcs/box/downloadReturnBox",
        contentType: "application/json;charset=UTF-8",
        data: clientId,
        dataType: "json",
        async: false,
        success: function (data) {
            console.log("data>" + JSON.stringify(data));
            if (data.code === 0) {

            } else {
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            BootstrapDialog.alert({
                title: "信息提示！",
                closable: false,
                message: XMLHttpRequest.responseJSON.msg
            });
        }
    });
}

//需要放入货箱的物品列表
function initOutBoxList(goodsBoxDetailList) {
    $('#merge-box-list').bootstrapTable({
        data: goodsBoxDetailList,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            return temp;
        }, onLoadSuccess: function (data) {
            $("#merge-box-list").bootstrapTable("load", list);
        },
        columns: [{
            field: 'spuName',
            title: '商品'
        }, {
            field: 'supplierCode',
            title: '供应商'
        }, {
            field: 'quantity',
            title: '数量'
        }, {
            field: 'weight',
            title: '每份重量',
            formatter: function (value, row, index) {
                return (value / row.quantity).toFixed(2);
            }
        }, {
            field: 'shelfLife',
            title: '保质期'
        }, {
            field: 'temperatureCodeName',
            title: '温区名称'
        }, {
            field: 'temperatureCode',
            title: '温区编码',
            visible: false
        }, {
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatterRemove,
        }]
    });
}

function actionFormatterRemove(value, row, index, field) {
    let result = '';
    result += '<button type="button" id="' + row.id + '_entry" class="btn btn-primary" onclick="removeReturnEntry(\'' + row.id + '\')">移除</button>';
    return result;
}

//移除
function removeReturnEntry(id) {
    const orderRow = $('#merge-box-list').bootstrapTable('getRowByUniqueId', id);
    $('#merge-box-list').bootstrapTable('removeByUniqueId', id);
    insertRow(orderRow, 'merge-table-list', true);
}

//操作栏的格式化
function actionFormatter(value, row, index, field) {
    let result = '';
    console.log("row:" + JSON.stringify(row));
    // result += '<a href="javascript:;" class="btn btn-xs green" onclick="outOfStock(\'' + row.id + '\')" title="缺货"><span class="glyphicon glyphicon-pencil"></span></a>';
    result += '<button type="button" id="' + row.id + '_entry" class="btn btn-primary" onclick="returnEntry(\'' + row.id + '\')">入箱&nbsp;</button>';
    result += '<button type="button" id="' + row.id + '_loss" class="btn btn-primary"  onclick="frmLossDone(\'' + row.id + '\')">报损</button>';
    return result;
}

//退货商品列表
function initMergeBoxDetailList(saleOrderDetailList) {
    /*const list = new Array();
    for (let i = 0; i < saleOrderList.length; i++) {
        const arr = saleOrderList[i].list;
        if (arr != null && arr.length > 0) {
            for (let j = 0; j < arr.length; j++) {
                list.push(arr[j]);
            }
        }
    }*/
    console.log(">>>>>>>>>>>" + JSON.stringify(saleOrderDetailList));
    $('#merge-table-list').bootstrapTable({
        data: saleOrderDetailList,
        method: 'post',
        pagination: false,//不分页
        sortable: false, //不排序
        sidePagination: "server",
        uniqueId: 'id',
        striped: true,
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            let temp = $("#search-condition").serializeJSON();
            return temp;
        },
        onLoadSuccess: function (data) {
            $("#merge-table-list").bootstrapTable("load", saleOrderDetailList);
        },
        columns: [{
            field: 'spuName',
            title: '商品',
            formatter: function (value, row, index) {
                return value + "(" + row.skuCode + ")";
            }
        }, {
            field: 'supplierCode',
            title: '供应商'
        }, {
            field: 'quantity',
            title: '数量'
        }, {
            field: 'weight',
            title: '重量',
            formatter: function (value, row, index) {
                return value.toFixed(2);
            }
        }, {
            field: 'shelfLife',
            title: '保质期'
        }, {
            field: 'temperatureCodeName',
            title: '温区名称'
        }, {
            field: 'temperatureCode',
            title: '温区编码',
            visible: false
        }, {
            field: 'spuId',
            title: '原料',
            visible: false
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter,
        }]
    });
}


//原料报损
function frmLose() {
    $('#frm-lose-select').html('');
    let html = '';
    const boxList = $('#merge-table-list').bootstrapTable('getData');
    if (boxList && boxList.length > 0) {
        let flag = false;
        for (let i = 0; i < boxList.length; i++) {
            const boxDetail = boxList[i];
            // if (boxDetail.spuName && boxDetail.id) {
            if (boxDetail.id) {
                if (!flag) {
                    $('#goods-detail-id').val(boxDetail.id);
                }
                flag = true;
                html += '<option value="' + boxDetail.id + '" class="opt-frm-inf" style="height: 30px;padding-top: 5px;">' + boxDetail.spuName + '&nbsp;&nbsp;/&nbsp;&nbsp;' + boxDetail.weight + '</option>';
            }
        }
    }
    $('#frm-lose-select').append(html);
    $('#frm-lose-select').selectpicker('refresh');
    $('#frm-lose-model').modal({
        keyboard: false
    })
    sortWeightInfo("merge-table-list", sortWeightId, sortTyp, 1, null, 0);
}

//原料报损：取消/报损->false/true
function frmLoseClick(cancel) {
    if (cancel) {
        const id = $('#goods-detail-id').val();
        if (!id) {
            BootstrapDialog.alert("请选择报损原料");
            return;
        }
        const frmLoseWeight = $('#frm-lose-weight').val();
        if (!checkPrice(frmLoseWeight)) {
            BootstrapDialog.alert("输入重量格式不符");
            return;
        }
        const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', id);
        console.log("合箱原料：" + JSON.stringify(orderRow));
        if (orderRow) {
            if (frmLoseWeight > orderRow.weight) {
                BootstrapDialog.alert("报损重量大于货箱内原料重量");
                return;
            } else {
                console.log("货箱信息更改前：" + JSON.stringify(orderRow));
                $('#merge-table-list').bootstrapTable('removeByUniqueId', id);
                orderRow.weight = parseFloat(orderRow.weight - frmLoseWeight).toFixed(2);
                console.log("货箱信息更改后：" + JSON.stringify(orderRow));
                insertRow(orderRow, 'merge-table-list', true);
            }
        } else {
            BootstrapDialog.alert("报损原料信息不存在");
            return;
        }
        $('#from-lose-goods-detail-box-code').val($('#merge-box-code').text());
        const opt = $("#form-frm-lose").serializeJSON();
        opt['clientId'] = $('#client-id').val();
        opt['boxCode'] = $('#merge-box-code').text();
        opt['type'] = 1;
        $.ajax({
            type: "POST",
            url: "/wcs/box/detail/updateFrmLoseById",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(opt),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    $('#frm-lose-model').modal('hide');
                } else {
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                    }
                }
            }
        });
    } else {
        console.log("2222222222222");
    }
}

//分拣称重socketIo响应
function electronicWeightCallBack(data) {
    console.log("称重数据返回：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.weight) {
            sortWeightInfo("sort-spu-table", sortWeightId, sortTyp, 0, vc, 0);
        } else {
            console.log("分拣/报损称重异常：" + data);
        }
    }
}

//入库缓存位扫码响应
function pageEntryCallBack(data) {
    console.log("入库缓存位扫码响应：" + data);
    if (data) {
        const vc = JSON.parse(data);
        if (vc.code == 0) {
            const resultData = vc.data;
        }
    }
}

//强制入库
function entryForce() {
    const boxCode = $('#merge-box-code').text();
    if (!boxCode) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }
    $('#ware-box-code').val(boxCode);
    $('#goods-box-code').val(boxCode);
    BootstrapDialog.confirm({
        title: '信息提示',
        message: '是否强制入库?',
        btnCancelLabel: '取消', // <-- Default value is 'Cancel',
        btnOKLabel: '确定', // <-- Default value is 'OK',
        callback: function (result) {
            if (!result) {
                return;
            }
            //材料箱
            const ops = $("#form-param").serializeJSON();
            //原料箱剩余物料
            const entry = $('#merge-box-list').bootstrapTable('getData');
            if (entry && entry.length > 0) {
                ops['detailList'] = entry;
            }
            ops['returnEntry'] = true;
            $('#sort-box-up-force').hide();
            $.ajax({
                type: "POST",
                url: "/wcs/returnEntry",
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(ops),
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    if (data.code == 0) {

                    } else {
                        $('#sort-box-up-force').show();
                        $('#merge-box-code').text($('#goods-box-code').val());
                        BootstrapDialog.alert(data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.responseJSON) {
                        if (XMLHttpRequest.responseJSON.msg) {
                            BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                        } else {
                            BootstrapDialog.alert(XMLHttpRequest.responseJSON.message);
                        }
                    }
                }
            });
        }
    });
}

//退货入库
function mergeBoxUp() {
    const boxCode = $('#merge-box-code').text();
    if (!boxCode) {
        BootstrapDialog.alert("货箱编号为空");
        return;
    }
    $('#ware-box-code').val(boxCode);
    $('#goods-box-code').val(boxCode);
    const opt = $("#form-param").serializeJSON();
    const entry = $('#merge-box-list').bootstrapTable('getData');
    if (entry && entry.length > 0) {
        opt['detailList'] = entry;
    }
    console.log("销售退货入库:" + JSON.stringify(opt));
    $('#merge-btn').hide();
    $('#merge-box-up').hide();

    //非空箱
    $.ajax({
        type: "POST",
        url: "/wcs/returnEntry",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(opt),
        dataType: "json",
        success: function (data) {
            if (data.code == 0) {
            } else {
                $('#merge-btn').show();
                $('#merge-box-up').show();
                BootstrapDialog.alert(data.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.responseJSON) {
                if (XMLHttpRequest.responseJSON.msg) {
                    BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                } else {
                    XMLHttpRequest.responseJSON.message
                }
            }
        }
    });
}

/**
 * 放入货箱
 * @param id
 */
function returnEntry(id) {
    const orderRow = $('#merge-table-list').bootstrapTable('getRowByUniqueId', id);
    if (orderRow) {
        let ops = {};
        ops['temperatureZoneCode'] = actTemperatureCode;
        ops['id'] = orderRow.spuId;
        $.ajax({
            type: "POST",
            url: "/wcs/spu/selectByIdAndTemperatureCode",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(ops),
            dataType: "json",
            success: function (data) {
                if (data.code == 0) {
                    insertRow(orderRow, 'merge-box-list', true);
                    $('#merge-table-list').bootstrapTable('removeByUniqueId', orderRow.id);
                } else {
                    BootstrapDialog.alert(data.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.responseJSON) {
                    if (XMLHttpRequest.responseJSON.msg) {
                        BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                    } else {
                        XMLHttpRequest.responseJSON.message
                    }
                }
            }
        });
    }
}

//仓库报损
function frmLossDone(id) {
    const ops = {};
    const opt = {};
    opt['saleOrderDetailId'] = id;
    ops['data'] = opt;
    BootstrapDialog.confirm({
        title: "信息提示",
        message: "是否要执行报损操作?",
        btnCancelLabel: '取消',
        btnOKLabel: '确认',
        callback: function (result) {
            // 点击确定按钮时，result为true
            if (result) {
                $.ajax({
                    type: "POST",
                    url: "/wcs/record/frm/loss/done",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(ops),
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 0) {
                            $('#merge-table-list').bootstrapTable('removeByUniqueId', id);
                        } else {
                            BootstrapDialog.alert(data.msg);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (XMLHttpRequest.responseJSON) {
                            if (XMLHttpRequest.responseJSON.msg) {
                                BootstrapDialog.alert(XMLHttpRequest.responseJSON.msg);
                            } else {
                                XMLHttpRequest.responseJSON.message
                            }
                        }
                    }
                });
            } else {
                // window.history.back();
            }
        }
    });
}